package org.vaadin.example.views;


import cn.hutool.core.util.StrUtil;
import com.vaadin.flow.component.UI;
import com.vaadin.flow.component.applayout.AppLayout;
import com.vaadin.flow.component.applayout.DrawerToggle;
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.button.ButtonVariant;
import com.vaadin.flow.component.combobox.ComboBox;
import com.vaadin.flow.component.dependency.CssImport;
import com.vaadin.flow.component.html.*;
import com.vaadin.flow.component.icon.SvgIcon;
import com.vaadin.flow.component.orderedlayout.Scroller;
import com.vaadin.flow.component.sidenav.SideNav;
import com.vaadin.flow.component.sidenav.SideNavItem;
import com.vaadin.flow.server.VaadinRequest;
import com.vaadin.flow.server.menu.MenuConfiguration;
import com.vaadin.flow.server.menu.MenuEntry;
import com.vaadin.flow.spring.security.AuthenticationContext;
import com.vaadin.flow.theme.lumo.LumoUtility;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
//import org.vaadin.example.cfg.SecurityService;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.vaadin.example.cfg.SecurityService;
import org.vaadin.example.security.SecurityService;
import org.vaadin.example.util.I18nUtil;
import org.vaadin.lineawesome.LineAwesomeIcon;

import java.util.List;
import java.util.Locale;

/**
 * The main view is a top-level placeholder for other views.
 */
//@CssImport("main-layout.css")
@Slf4j
//@Route("") // 作为主视图
//@Layout
//@AnonymousAllowed
public class MainLayout extends AppLayout {

    private H1 viewTitle;

    private Locale browserLocale ;

    private boolean isFullscreen = false;
//    private final SecurityService securityService;

    private final SecurityService securityService;



    public MainLayout(SecurityService securityService, HttpServletRequest request, HttpServletResponse response) {
        this.securityService = securityService;

        String cokStr = null;
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if ("myCookie".equals(cookie.getName())) {
                    System.out.println("Cookie Value: " + cookie.getValue());
                    cokStr = cookie.getValue();
                }
            }
        }

        if (cokStr==null){
            browserLocale = VaadinRequest.getCurrent().getLocale();
        }else {
            browserLocale = new Locale(cokStr);
        }


        setPrimarySection(Section.DRAWER);
        addDrawerContent();
        addHeaderContent(request, response);
    }

    private void addHeaderContent(HttpServletRequest request, HttpServletResponse response) {
        DrawerToggle toggle = new DrawerToggle();
        toggle.setClassName("drawer-toggle-border");
        toggle.setAriaLabel("Menu toggle");
        toggle.addClickListener(event -> {
            int clickCount = event.getClickCount();
            System.out.println(clickCount);
        });

        viewTitle = new H1();
        viewTitle.addClassNames(LumoUtility.FontSize.LARGE, LumoUtility.Margin.NONE);


        String exitFullscreenText = I18nUtil.getMessage("ExitFullscreen", browserLocale);
        String toggleFullscreenText = I18nUtil.getMessage("ToggleFullscreen", browserLocale);

        Button fullscreenButton = new Button("Toggle Fullscreen");
        fullscreenButton.addClassName("float-fullscreenButton");
        fullscreenButton.setText(isFullscreen ? exitFullscreenText : toggleFullscreenText);
        fullscreenButton.addClickListener(event -> {
            if (isFullscreen) {
                getElement().executeJs("document.exitFullscreen();");
            } else {
                getElement().executeJs("var elem = document.documentElement; " +
                        "if (elem.requestFullscreen) { elem.requestFullscreen(); } " +
                        "else if (elem.webkitRequestFullscreen) { elem.webkitRequestFullscreen(); } " +
                        "else if (elem.msRequestFullscreen) { elem.msRequestFullscreen(); } " +
                        "else if (elem.mozRequestFullScreen) { elem.mozRequestFullScreen(); } " +
                        "else { Notification.show('Fullscreen not supported by this browser.'); }");
            }
            isFullscreen = !isFullscreen;
            fullscreenButton.setText(isFullscreen ? exitFullscreenText : toggleFullscreenText);
        });



        ComboBox<String> comboBox = new ComboBox<>();
        comboBox.setWidth("130px");
        comboBox.setPrefixComponent(LineAwesomeIcon.LANGUAGE_SOLID.create());
        comboBox.addClassName("float-comboBox");
        comboBox.setItems(List.of("English","中文"));
        if (browserLocale.toString().contains("en")){
            comboBox.setValue("English");
        }else {
            comboBox.setValue("中文");
        }
        comboBox.addValueChangeListener(event->{
            String value = event.getValue();
            System.err.println(value);
            if ("English".equals(value)){
                browserLocale = Locale.US;
            }else {
                browserLocale = Locale.CHINA;
            }
            log.info("browserLocale2:{}", browserLocale);
            Cookie cookie = new Cookie("myCookie", browserLocale.toString());
            cookie.setPath("/");
            cookie.setMaxAge(60 * 60); // Set the cookie to expire in 1 hour
            response.addCookie(cookie);
            UI.getCurrent().getPage().reload();
        });




        String logoutText = I18nUtil.getMessage("LogOut", browserLocale);

        String u = securityService.getAuthenticatedUser().getUsername();

//        String u = securityService.getAuthenticatedUser().getUsername();

        Button test = new Button(logoutText+" "+u);
        test.setWidth("190px");
        test.addThemeVariants(ButtonVariant.LUMO_PRIMARY, ButtonVariant.LUMO_ERROR);
        test.addClassNames(LumoUtility.FontSize.LARGE);
        test.setPrefixComponent(LineAwesomeIcon.POWER_OFF_SOLID.create());
        test.addClassName("float-logout-button");
        test.addClickListener(event -> {
//            securityService.logout();
            log.info("user:{} logged out",u);

            securityService.logout();
            //跳转到login路由
//            getUI().ifPresent(ui -> ui.navigate("login"));
        });




        addToNavbar(true, toggle,viewTitle,fullscreenButton,comboBox, test);



    }




    private void addDrawerContent() {
        Span appName = new Span("My Web App");
        appName.addClassNames(LumoUtility.FontWeight.SEMIBOLD, LumoUtility.FontSize.LARGE);
        Header header = new Header(appName);

        Scroller scroller = new Scroller(createNavigation());

        addToDrawer(header, scroller, createFooter());
    }




    private SideNav createNavigation() {
        SideNav nav = new SideNav();

        List<MenuEntry> menuEntries = MenuConfiguration.getMenuEntries();
        menuEntries.forEach(entry -> {
            log.info("menuEntries:{}", entry);
            String pageTitleText = I18nUtil.getMessage(entry.title(), browserLocale);
            if (entry.icon() != null) {
//                nav.addItem(new SideNavItem(entry.title(), entry.path(), new SvgIcon(entry.icon())));
                nav.addItem(new SideNavItem(pageTitleText, entry.path(), new SvgIcon(entry.icon())));
            } else {
//                nav.addItem(new SideNavItem(entry.title(), entry.path()));
                nav.addItem(new SideNavItem(pageTitleText, entry.path()));
            }
        });

        return nav;
    }

    private Footer createFooter() {
        Footer layout = new Footer();

        return layout;
    }

    @Override
    protected void afterNavigation() {
        super.afterNavigation();
        viewTitle.setText(getCurrentPageTitle());
    }

    private String getCurrentPageTitle() {
        String str = MenuConfiguration.getPageHeader(getContent()).orElse("");
        log.info("getCurrentPageTitle:{}", str);
        return I18nUtil.getMessage(str, browserLocale);
    }
}

